package com.anyikang.volunteer.sos.volunteer.app.spot;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.anyikang.volunteer.sos.volunteer.R;
import com.anyikang.volunteer.sos.volunteer.app.MyConstant;
import com.anyikang.volunteer.sos.volunteer.app.adapter.GridImageAdapter;
import com.anyikang.volunteer.sos.volunteer.app.bean.MyCurrentOrder;
import com.anyikang.volunteer.sos.volunteer.app.bean.User;
import com.anyikang.volunteer.sos.volunteer.app.view.FullyGridLayoutManager;
import com.anyikang.volunteer.sos.volunteer.utils.ToastUtils;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.LocalMediaLoader;
import com.luck.picture.lib.model.PictureConfig;

import com.lzy.okhttpserver.listener.UploadListener;
import com.lzy.okhttpserver.task.ExecutorWithListener;
import com.lzy.okhttpserver.upload.UploadInfo;
import com.lzy.okhttpserver.upload.UploadManager;
import com.yalantis.ucrop.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Response;

/**
 * 现场实录，拍照和视频
 * 
 */
public class
SpotFragment extends Fragment implements View.OnClickListener ,ExecutorWithListener.OnAllTaskEndListener{

	private View layout;
	private RecyclerView recyclerPic;
	private RecyclerView recyclerVideo;

	private Activity mActivity;
	private GridImageAdapter adapterPic;
	private GridImageAdapter adapterVideo;
	private List<LocalMedia> selectMediaPic = new ArrayList<>();
	private List<LocalMedia> selectMediaVideo = new ArrayList<>();

	private int compressFlag = 1; //1系统自带压缩，2第三方luban压缩压缩
	private boolean theme = false;
	private boolean selectImageType = true; //是否图片类型
	int selectType = LocalMediaLoader.TYPE_VIDEO;
	String mTaskOrderId;

	Button btUploadPic;  //上传图片
	Button btUploadVideo;//上传视频

	String TAG = "SpotFragment";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Log.i(TAG,"onCreateView");

		layout = inflater.inflate(R.layout.fragment_spot, container, false);
		initView();

		UploadManager.getInstance(mActivity).getThreadPool().setCorePoolSize(2); //progress
		UploadManager.getInstance(mActivity).getThreadPool().getExecutor().addOnAllTaskEndListener(this);
		return layout;
	}



	@Override
	public void onAttach(Context context) {
		Log.i(TAG,"onAttach");

		mActivity = (Activity) context;
		super.onAttach(context);
	}

	private void initView() {

		//标题
		TextView tvTitle = (TextView) layout.findViewById(R.id.tv_title);
		tvTitle.setText("现场");

		ImageButton imgBtLeft = (ImageButton) layout.findViewById(R.id.imgBtLeft);
		imgBtLeft.setVisibility(View.GONE);

		//图片选择
		recyclerPic = (RecyclerView) layout.findViewById(R.id.recyclerPic);
		FullyGridLayoutManager manager = new FullyGridLayoutManager(mActivity, 4, GridLayoutManager.VERTICAL, false);
		recyclerPic.setLayoutManager(manager);
		AddPicClickListerner addpicListener = new AddPicClickListerner();
		int gridWidth = recyclerPic.getWidth();
		Log.i(TAG,"gridWidth="+gridWidth);
		adapterPic = new GridImageAdapter(mActivity, addpicListener,recyclerPic.getWidth());
		adapterPic.setSelectMax(3);
		recyclerPic.setAdapter(adapterPic);

		//视频选择
		recyclerVideo = (RecyclerView) layout.findViewById(R.id.recyclerVideo);
		FullyGridLayoutManager managerVideo = new FullyGridLayoutManager(mActivity, 4, GridLayoutManager.VERTICAL, false);
		recyclerVideo.setLayoutManager(managerVideo);
		AddVideoClickListerner addVideoListener = new AddVideoClickListerner();
		int gridWidth2 = recyclerVideo.getWidth();
		Log.i(TAG,"gridWidth2="+gridWidth);
		adapterVideo = new GridImageAdapter(mActivity, addVideoListener,recyclerVideo.getWidth());
		adapterVideo.setSelectMax(3);
		recyclerVideo.setAdapter(adapterVideo);

		//上传图片
		btUploadPic = (Button) layout.findViewById(R.id.btUploadPic);
		btUploadPic.setOnClickListener(this);

		//上传视频
		btUploadVideo = (Button) layout.findViewById(R.id.btUploadVideo);
		btUploadVideo.setOnClickListener(this);
	}

	@Override
	public void onHiddenChanged(boolean hidden) {

		Log.i(TAG,"onHiddenChanged="+hidden);
		super.onHiddenChanged(hidden);
	}


	@Override
	public void onStart() {
		Log.i(TAG,"onStart");
		super.onStart();
	}

	@Override
	public void onResume() {
		Log.i(TAG,"onResume");
		super.onResume();
	}

	@Override
	public void onStop() {
		Log.i(TAG,"onStop");
		super.onStop();
	}

	@Override
	public void onAllTaskEnd() {
		Log.i(TAG,"onAllTaskEnd");
		for (UploadInfo uploadInfo : UploadManager.getInstance(mActivity).getAllTask()) {
			if (uploadInfo.getState() != UploadManager.FINISH) {
				//GXW-Toast.makeText(getContext(), "所有上传线程结束，部分上传未完成", Toast.LENGTH_SHORT).show();
				Log.i(TAG,"所有上传线程结束，部分上传未完成");
				btUploadVideo.setEnabled(true);
				btUploadPic.setEnabled(true);
				return;
			}
		}

		btUploadVideo.setEnabled(true);
		btUploadPic.setEnabled(true);
		//Toast.makeText(getContext(), "所有上传任务完成", Toast.LENGTH_SHORT).show();
		Log.i(TAG,"所有上传任务完成");
	}

	private class MyUploadListener extends UploadListener<UploadInfo> {

		private GridImageAdapter.ViewHolder holder;

		@Override
		public void onProgress(UploadInfo uploadInfo) {
			Log.i(TAG,"onProgress"+uploadInfo.getProgress());
			//gxw-Log.e("MyUploadListener", "onProgress:" + uploadInfo.getFileName() + " " + uploadInfo.getTotalLength() + " " + uploadInfo.getUploadLength() + " " + uploadInfo.getProgress());
			GridImageAdapter.ViewHolder view = (GridImageAdapter.ViewHolder) getUserTag();
			holder = view;
			holder.refresh(uploadInfo);
		}

		@Override
		public void onFinish(UploadInfo t) {
			Log.i(TAG,"onFinish");
			Log.e(TAG, "finish:" + t);
			holder.finish(t);
		}

		@Override
		public void onError(UploadInfo uploadInfo, String errorMsg, Exception e) {
			Log.i(TAG,"onError");
			Log.e(TAG, "onError:" + errorMsg);
			btUploadVideo.setEnabled(true);
			btUploadPic.setEnabled(true);
			if(e != null)
			{
				e.printStackTrace();
			}
			//GXW-
		}

		@Override
		public UploadInfo parseNetworkResponse(Response response) throws Exception {

			String ret = response.toString(); //gxw+
			Log.e(TAG, "parseNetworkResponse:" + ret);
			return null;
		}


	}

	@Override
	public void onDestroyView() {
		Log.i(TAG,"onDestroyView");
		try
		{
			UploadManager.getInstance(mActivity).getThreadPool().getExecutor().removeOnAllTaskEndListener(this);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		super.onDestroyView();
	}



	/**
	 * 图片回调接口
	 */
	public  class AddVideoClickListerner implements GridImageAdapter.onAddPicClickListener{

		public void onAddPicClick(int type, int position) {
			switch (type) {
				case 0:

			/*gxw-s	裁剪宽，高

				    String ws = et_w.getText().toString().trim();
					String hs = et_h.getText().toString().trim();

					if (!isNull(ws) && !isNull(hs)) {
						cropW = Integer.parseInt(ws);
						cropH = Integer.parseInt(hs);
					}

             gxw-e*/

			  /* LuBan压缩宽高

					if (!isNull(et_compress_width.getText().toString()) && !isNull(et_compress_height.getText().toString())) {
						compressW = Integer.parseInt(et_compress_width.getText().toString());
						compressH = Integer.parseInt(et_compress_height.getText().toString());
					}
				*/

					int selector = R.drawable.select_cb;
					int selectMode = 1;//多选
					boolean isShow = true; //显示拍照选项，不但可以选择现有图片，还可以拍照
					boolean enablePreview = true;  //是否启用预览
					boolean enableCrop = false;  //是否启用裁剪
					boolean isPreviewVideo = true;  //是否启用预览视频
					boolean isCheckNumMode = false;  //启用，多选时，图片右上角显示数字

					FunctionConfig config = new FunctionConfig();
					config.setType(LocalMediaLoader.TYPE_VIDEO);  //是选择图片还是视频
					config.setCopyMode(1); //裁剪模式1:1
					config.setCompress(false); //默认不压缩图片
					config.setEnablePixelCompress(true);
					config.setEnableQualityCompress(true);
					config.setMaxSelectNum(3);  //最多可以选择的图片数量
					config.setMaxSelectVideo(2);
					config.setSelectMode(selectMode);
					config.setShowCamera(isShow);
					config.setEnablePreview(enablePreview);
					config.setEnableCrop(enableCrop);
					config.setPreviewVideo(isPreviewVideo);
					config.setRecordVideoDefinition(FunctionConfig.HIGH);// 视频清晰度
					config.setRecordVideoSecond(60);// 视频秒数

					/*gxw-s 裁剪宽高
					config.setCropW(cropW);
					config.setCropH(cropH);
					gxw-e*/
					config.setCheckNumMode(isCheckNumMode);
					config.setCompressQuality(100);
					config.setImageSpanCount(4);
					config.setSelectMedia(selectMediaVideo);
					config.setCompressFlag(compressFlag);

					/*gxw-s 压缩宽高
					  config.setCompressW(compressW);
					  config.setCompressH(compressH);

					if (theme) {  蓝色主题
						config.setThemeStyle(ContextCompat.getColor(MainActivity.this, R.color.blue));
						// 可以自定义底部 预览 完成 文字的颜色和背景色
						if (!isCheckNumMode) {
							// QQ 风格模式下 这里自己搭配颜色，使用蓝色可能会不好看
							config.setPreviewColor(ContextCompat.getColor(MainActivity.this, R.color.white));
							config.setCompleteColor(ContextCompat.getColor(MainActivity.this, R.color.white));
							config.setPreviewBottomBgColor(ContextCompat.getColor(MainActivity.this, R.color.blue));
							config.setBottomBgColor(ContextCompat.getColor(MainActivity.this, R.color.blue));
						}
					}gxw-e*/

						config.setCheckedBoxDrawable(selector);


					// 先初始化参数配置，在启动相册
					PictureConfig.init(config);
					PictureConfig.getPictureConfig().openPhoto(mActivity, resultCallbackVideo);

					break;
				case 1:
					// 删除视频
					selectMediaVideo.remove(position);
					adapterVideo.notifyItemRemoved(position);
					break;
			}
		}
	};
	/**
	 * 删除图片回调接口
	 */

	public  class AddPicClickListerner implements GridImageAdapter.onAddPicClickListener{

		@Override
		public void onAddPicClick(int type, int position) {
			switch (type) {
				case 0:
					// 进入相册

			/*gxw-s	裁剪宽，高暂时不需要
				    String ws = et_w.getText().toString().trim();
					String hs = et_h.getText().toString().trim();
					if (!isNull(ws) && !isNull(hs)) {
						cropW = Integer.parseInt(ws);
						cropH = Integer.parseInt(hs);
					}


					LuBan压缩宽高，暂时不需要

					if (!isNull(et_compress_width.getText().toString()) && !isNull(et_compress_height.getText().toString())) {
						compressW = Integer.parseInt(et_compress_width.getText().toString());
						compressH = Integer.parseInt(et_compress_height.getText().toString());
					}
             gxw-e*/
					int selector = R.drawable.select_cb;

					int selectMode = 1;//多选
					boolean isShow = true; //显示拍照选项，不但可以选择现有图片，还可以拍照
					boolean enablePreview = true;  //是否启用预览
					boolean enableCrop = false;  //是否启用裁剪
					boolean isPreviewVideo = true;  //是否启用预览视频
					boolean isCheckNumMode = false;  //启用，多选时，图片右上角显示数字

					FunctionConfig config = new FunctionConfig();
					config.setType(LocalMediaLoader.TYPE_IMAGE);  //是选择图片还是视频
					config.setCopyMode(1); //裁剪模式1:1
					config.setCompress(false); //默认不压缩图片
					config.setEnablePixelCompress(true);
					config.setEnableQualityCompress(true);
					config.setMaxSelectNum(3);  //最多可以选择的图片数量
					config.setMaxSelectVideo(2);
					config.setSelectMode(selectMode);
					config.setShowCamera(isShow);
					config.setEnablePreview(enablePreview);
					config.setEnableCrop(enableCrop);
					config.setPreviewVideo(isPreviewVideo);
					config.setRecordVideoDefinition(FunctionConfig.HIGH);// 视频清晰度
					config.setRecordVideoSecond(60);// 视频秒数

					/*gxw-s 裁剪宽高
					config.setCropW(cropW);
					config.setCropH(cropH);
					gxw-e*/
					config.setCheckNumMode(isCheckNumMode);
					config.setCompressQuality(100);
					config.setImageSpanCount(4);
					config.setSelectMedia(selectMediaPic);
					config.setCompressFlag(compressFlag);

					/*gxw-s 压缩宽高
					  config.setCompressW(compressW);
					  config.setCompressH(compressH);

					if (theme) {  蓝色主题
						config.setThemeStyle(ContextCompat.getColor(MainActivity.this, R.color.blue));
						// 可以自定义底部 预览 完成 文字的颜色和背景色
						if (!isCheckNumMode) {
							// QQ 风格模式下 这里自己搭配颜色，使用蓝色可能会不好看
							config.setPreviewColor(ContextCompat.getColor(MainActivity.this, R.color.white));
							config.setCompleteColor(ContextCompat.getColor(MainActivity.this, R.color.white));
							config.setPreviewBottomBgColor(ContextCompat.getColor(MainActivity.this, R.color.blue));
							config.setBottomBgColor(ContextCompat.getColor(MainActivity.this, R.color.blue));
						}
					}gxw-e*/
					/*gxw-s 视频类型不需要 if (selectImageType) {
						config.setCheckedBoxDrawable(selector);
					}gxw-e*/
                    config.setCheckedBoxDrawable(selector);
					// 先初始化参数配置，在启动相册
					PictureConfig.init(config);
					PictureConfig.getPictureConfig().openPhoto(mActivity, resultCallback);
					// 只拍照
					//PictureConfig.getPictureConfig().startOpenCamera(mContext, resultCallback);
					break;
				case 1:
					// 删除图片或视频
					selectMediaPic.remove(position);
					adapterPic.notifyItemRemoved(position);
					break;
			}
		}
	};

	/**
	 * 图片回调方法
	 */
	private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {
		@Override
		public void onSelectSuccess(List<LocalMedia> resultList) {
			selectMediaPic = resultList;
			Log.i("callBack_result", selectMediaPic.size() + "");
			if (selectMediaPic != null) {

					adapterPic.setList(selectMediaPic);
			recyclerPic.setAdapter(adapterPic);

			//	adapterPic.notifyDataSetChanged();
			}
		}
	};


	/**
	 * 视频回调方法
	 */
	private PictureConfig.OnSelectResultCallback resultCallbackVideo = new PictureConfig.OnSelectResultCallback() {
		@Override
		public void onSelectSuccess(List<LocalMedia> resultList) {
			selectMediaVideo = resultList;
			Log.i("callBack_result", selectMediaVideo.size() + "");
			if (selectMediaVideo != null) {
				adapterVideo.setList(selectMediaVideo);
				recyclerVideo.setAdapter(adapterVideo);
			//    adapterVideo.notifyDataSetChanged();
			}
		}
	};
	public static final String SERVER = "http://server.jeasonlzy.com/OkHttpUtils/";
	//public static final String SERVER = "http://192.168.1.40:8080/ReceiveFile/servlet/ReceiveFileServlet";
	//gxw-public static final String URL_FORM_UPLOAD = SERVER+"upload";

	String URL_FORM_UPLOAD = "http://192.168.1.104:8080/ReceiveFile/servlet/ReceiveFileServlet"; //换成自己的测试url地址gxw+


	/**
	 * 是否可上传，根据任务单状态判断，当为2和3时可以上传
	 * @return
	 */
	public boolean isUpload()
	{
		MyCurrentOrder currentOrder = new MyCurrentOrder(mActivity);
		String itemId = currentOrder.getItemId();

		if(!TextUtils.isEmpty(itemId))
		{
			int state = currentOrder.getState();
			if(state == 4)
			{
				ToastUtils.showToast(mActivity,"已提交报告");
				return false;
			}
			else  //2和3
			{
				mTaskOrderId = itemId;
				return true;
			}

		}
		else
		{
			ToastUtils.showToast(mActivity,"还没有接受任务");
			return false;
		}


	}

	@Override
	public void onClick(View view) {
		switch (view.getId())
		{
			case R.id.btUploadPic:
				if (selectMediaPic != null) {

					if (!isUpload())
					{
						return;
					}
					for (int i = 0; i < selectMediaPic.size(); i++) {
						MyUploadListener listener = new MyUploadListener();
						View childView = recyclerPic.getChildAt(i);
						listener.setUserTag(recyclerPic.getChildViewHolder(childView));

                        User user = new User(mActivity);
                        String token = user.getUserToken();
						HashMap<String ,String> paramMap = new HashMap<String,String>();
						paramMap.put("tokenId",token);
						paramMap.put("orderId",mTaskOrderId);
						Log.i(TAG,"tokenId="+token);
						Log.i(TAG,"orderId="+mTaskOrderId);
						UploadManager.getInstance(mActivity).addTask(MyConstant.API_SPOT_IMAGE, new File(selectMediaPic.get(i).getPath()), "file",paramMap, listener);
						

					/*	if(i == 0)
						btUploadPic.setEnabled(false);*/
						//	UploadManager.getInstance(mActivity).addTask(Urls.URL_FORM_UPLOAD, new File(images.get(i).path), "imageFile", listener);

					}
				}
				break;

			case R.id.btUploadVideo:

				if (selectMediaVideo != null) {

					if (!isUpload())  //还没有接单
					{
						return;
					}

					for (int i = 0; i < selectMediaVideo.size(); i++) {
						MyUploadListener listener = new MyUploadListener();
						View childView = recyclerVideo.getChildAt(i);
						listener.setUserTag(recyclerVideo.getChildViewHolder(childView));
						HashMap<String ,String> paramMap = new HashMap<String,String>();
						User user = new User(mActivity);
                        String token = user.getUserToken();
						paramMap.put("tokenId",token);
						paramMap.put("orderId",mTaskOrderId);
						UploadManager.getInstance(mActivity).addTask(MyConstant.API_SPOT_VIDEO, new File(selectMediaVideo.get(i).getPath()), "file",paramMap, listener);


						/*if(i == 0)
						 	btUploadVideo.setEnabled(false);*/
						//UploadManager.getInstance(mActivity).addTask(URL_FORM_UPLOAD, new File(selectMediaVideo.get(i).getPath()), "videoFile"+(i+1), listener);
						//	UploadManager.getInstance(mActivity).addTask(Urls.URL_FORM_UPLOAD, new File(images.get(i).path), "imageFile", listener);
					}
				}
				break;
		}

	}
}
